package com.faxsun.web.controller.admin;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import mblog.web.controller.BaseController;
import mtons.modules.pojos.Data;
import mtons.modules.pojos.Page;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.faxsun.core.persist.entity.LivePO;
import com.faxsun.core.service.WechatService;
import com.faxsun.web.controller.admin.url.AdminViewConstants;

/**
 * 直播管理
 * 
 * @author leima 2015-06-10
 *
 */
@Controller
@RequestMapping(value = "/admin/live")
public class LiveManagerController extends BaseController {

	private static final Logger log = LoggerFactory.getLogger(LiveManagerController.class);

	@Autowired
	WechatService wechatService;

	@Value("${live.ceremony.enddate}")
	private String endDate;

	@RequestMapping(method = RequestMethod.GET)
	public String list(ModelMap model) {
		model.addAttribute("url", "/admin/live/data-url");
		model.addAttribute(AdminViewConstants.VIEW, AdminViewConstants.VIEW_LIVE_LIST);

		return AdminViewConstants.VIEW_ADMIN_LAYOUT;
	}

	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String addView(ModelMap model) {
		model.addAttribute(AdminViewConstants.VIEW, AdminViewConstants.VIEW_LIVE_ADD);
		return AdminViewConstants.VIEW_ADMIN_LAYOUT;
	}

	@RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
	public String detailView(@PathVariable("id") Long id, ModelMap model) {
		if (id != null) {
			LivePO livePO = this.wechatService.findEventById(id);
			model.addAttribute("channel", livePO);
		}
		model.addAttribute(AdminViewConstants.VIEW, AdminViewConstants.VIEW_LIVE_ADD);
		return AdminViewConstants.VIEW_ADMIN_LAYOUT;
	}

	@RequestMapping(value = "add", method = RequestMethod.POST)
	public String add(@RequestParam(value = "topic", required = true) String topic,
			@RequestParam(value = "startTime", required = true) String startTime,
			@RequestParam(value = "endTime", required = true) String endTime,
			@RequestParam(value = "url", required = false) String url,
			@RequestParam(value = "id", required = false) Long id,
			@RequestParam(value = "selected", required = false, defaultValue = "false") boolean isSelected,
			ModelMap model) {

		LivePO newEvent = null;
		if (id != null) {
			newEvent = this.wechatService.findEventById(id);
		}
		if (newEvent == null) {
			newEvent = new LivePO();
		}
		newEvent.setTopic(topic);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			newEvent.setStartTime(sdf.parse(startTime));

		} catch (ParseException e) {
			newEvent.setStartTime(new Date());
		}

		try {
			newEvent.setEndTime(sdf.parse(endTime));
		} catch (ParseException e) {
			try {
				newEvent.setEndTime(sdf.parse(endDate));
			} catch (ParseException e1) {
			}
		}
		if (!StringUtils.isEmpty(url)) {
			if (url.startsWith("/faxsun-info"))
				url = url.substring(12);
			newEvent.setCoverImage(url);
		}
		wechatService.saveEvent(newEvent);
		return "redirect:/admin/live";
	}

	/**
	 * JSON获取slive event数据{@link LivePO}
	 * 
	 * @param pageNo
	 * @param max
	 * @param search
	 * @param field
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/data-url", method = RequestMethod.GET)
	public @ResponseBody LiveTableJSON data(@RequestParam(value = "offset", required = false) Integer pageNo,
			@RequestParam(value = "limit", required = false) Integer max,
			@RequestParam(value = "search", required = false) String search,
			@RequestParam(value = "sort", required = false) String field, ModelMap model) {

		if (pageNo == null) {
			pageNo = 1;
		}
		if (max == null) {
			max = 10;
		}

		pageNo = pageNo / max + 1;
		Page page = wrapPage(pageNo);
		page.setMaxResults(max);

		if (StringUtils.isEmpty(search)) {
			page = wechatService.pagingAllEvent(page, true);
		} else {
			// 搜索结果
		}

		LiveTableJSON ret = new LiveTableJSON();
		ret.total = page.getTotalCount();

		ArrayList<LivePO> table = new ArrayList<LivePO>();
		for (LivePO event : (List<LivePO>) page.getResults()) {
			table.add(event);
		}
		ret.rows = table;

		return ret;
	}

	@RequestMapping(value = "setselected", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE
			+ ";charset=UTF-8")
	@ResponseBody
	public Data add(@RequestParam(value = "ids", required = true) String ids,
			@RequestParam(value = "selected", required = true) boolean isSelected) {
		Data ret = Data.failure("设置精选频道失败,频道" + ids + "不存在");

		String[] idArray = ids.split(",");
		boolean isAllSuccess = true;
		StringBuffer sb = new StringBuffer();
		for (String idString : idArray) {

			try {
				long id = Long.parseLong(idString);
				LivePO livePO = this.wechatService.findEventById(id);
				if (livePO != null) {
					livePO.setSelected(isSelected);
					this.wechatService.saveEvent(livePO);
				}
			} catch (Exception e) {
				log.error("", e);
				isAllSuccess = isAllSuccess && false;
				sb.append(idString);
				sb.append(",");
			}

		}
		if (isAllSuccess)
			ret = Data.success("设置精选频道成功");
		else {
			sb.deleteCharAt(sb.length() - 1);
			ret.setMessage("设置精选频道失败,频道" + sb.toString() + "设置失败");
		}
		return ret;
	}

}

class LiveTableJSON {
	public int total;
	public List<LivePO> rows;

}
